package com.bjypc.youth.util;

import java.io.File;
import java.util.Date;

import com.bjypc.youth.entity.ResearchArticle;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class WordReader {

	public WordReader() {
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String folder = "D:\\temp\\articles";
//		WordReader.extractDoc("D:\\temp\\articles\\代与代际关系研究\\“80年代生人”崭露头角.doc","d:\\“80年代生人”崭露头角.txt");
		// scan
		File file = new File(folder);
		File[] filesList = file.listFiles();
		int i = 0;
		for (File subFolder : filesList) {
			if (subFolder.isDirectory()) {
				String folderName = subFolder.getName();

				i++;
				// parse each articles into array
				parseArticle(subFolder, i, folderName);
			}
		}
	}
	private static void parseArticle(File subFolder, int articleNum, String folderName) {
		File[] articles = subFolder.listFiles();
		for (File article : articles) {
			String path = article.getAbsolutePath();
			String txtPath=path.replace(".doc", ".txt");
			System.out.println(articleNum+":Transforming "+path+" to "+ txtPath);
			WordReader.extractDoc(path, txtPath);
			System.out.println("sleep 5 seconds");
			try {
				Thread.sleep(5*1000);
			} catch (InterruptedException e) {
				
				e.printStackTrace();
			}finally{
				System.out.println("be awake.");
			}
			
			
		}
	}
	public static void extractDoc(String inputFIle, String outputFile) {

		boolean flag = false;

		// 打开Word应用程序

		ActiveXComponent app = new ActiveXComponent("Word.Application");

		try {

			// 设置word不可见

			app.setProperty("Visible", new Variant(false));

			// 打开word文件

			Dispatch doc1 = app.getProperty("Documents").toDispatch();

			Dispatch doc2 = Dispatch.invoke(
					doc1,
					"Open",
					Dispatch.Method,
					new Object[] { inputFIle, new Variant(false),
					new Variant(true) }, new int[1]).toDispatch();

			// 作为txt格式保存到临时文件

			Dispatch.invoke(doc2, "SaveAs", Dispatch.Method, new Object[] {

			outputFile, new Variant(7) }, new int[1]);

			// 关闭word

			Variant f = new Variant(false);

			Dispatch.call(doc2, "Close", f);

			flag = true;

		} catch (Exception e) {

			e.printStackTrace();

		} finally {

			app.invoke("Quit", new Variant[] {});

		}

		if (flag == true) {

			System.out.println("Transformed Successfully");

		} else {

			System.out.println("Transform Failed");

		}

	}
}
